package com.boco.pciv.service.shiro;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.core.entity.Constants;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.security.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

public class ShiroUtils {
    public static String encryptPassword(String userid,String password){
        String salt = genSalt(userid);
        //user.setPassword(new SimpleHash(Constants.SecHashAlgorithmName, password, salt, Constants.SecHashIterations).toString());
        return new SimpleHash(Constants.SecHashAlgorithmName, password, salt, Constants.SecHashIterations).toString();
    }
    public static void encryptPassword(LoginUser user){
        user.setPassword(encryptPassword(user.getUserId(),user.getPassword()));
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static LoginUser getUserEntity() {
        return (LoginUser)SecurityUtils.getSubject().getPrincipal();
    }

    public static String getUserId() {
        return getUserEntity().getUserId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if(kaptcha == null){
            throw new PcivException("验证码已失效");
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

    public static String genSalt(String user){
        String soltStr = StrUtil.format("Nscs:{}",user);
        return  soltStr;
    }
}
